package com.next.aappublicapp.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.util.Log;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.gson.Gson;
import com.next.aap.client.RegisterFacebookUserProfile;
import com.next.aap.messages.FacebookUserRegisteredMessage;
import com.next.aappublicapp.server.service.DataServices;

public class UserProfileUtil {
	private static final String USER_PROFILE = "USER_PROFILE";
	private static final String USER_PROFILE_SAVED_BY_USER = "USER_PROFILE_SAVED_BY_USER";
	private static final String USER_PROFILE_SAVED_OBJECT = "USER_PROFILE_SAVED_OBJECT";
	private static final String USER_REGISTERED_ON_SERVER = "USER_REGISTERED_ON_SERVER";
	//ID of User attached 
	private static final String USER_ID = "USER_ID";

	/**
	 * This function will be called to check if user has saved profile previously, if yes then we will not show profile screen
	 * This function will also check if previous save attempt on server was succesfull, if not then it will retry again
	 * @param context
	 * @return
	 */
	public static boolean isUserProfiledSavedByUser(Context context){
		boolean savedByUser = false;
		try{
			Log.i("Raavi", "Checking if User has saved Profile before");
			final SharedPreferences prefs = context.getSharedPreferences(USER_PROFILE, Context.MODE_PRIVATE);
			savedByUser = prefs.getBoolean(USER_PROFILE_SAVED_BY_USER, false);
			Log.i("Raavi", "Facebook User saved by User " + savedByUser);
			if(savedByUser){
				//If saved by user then only check if its aved on server or not
				checkAndSaveProfileInternal(prefs, context);
			}
		}catch(Exception ex){
			EasyTracker.getTracker().sendException("isUserProfiledSavedByUser", ex, true);
		}
		
		return savedByUser;
	}
	
	public static void onUserRegistered(Context context, FacebookUserRegisteredMessage facebookUserRegisteredMessage){
		try{
			Log.i("Ravi", "User saved on Server");
			final SharedPreferences prefs = context.getSharedPreferences(USER_PROFILE, Context.MODE_PRIVATE);
			Editor editor = prefs.edit();
			editor.putBoolean(USER_REGISTERED_ON_SERVER, true);
			editor.putLong(USER_ID, facebookUserRegisteredMessage.getUserId());
			editor.commit();
		}catch(Exception ex){
			EasyTracker.getTracker().sendException("onUserRegistered", ex, true);
		}
	}
		
	private static void checkAndSaveProfileInternal(final SharedPreferences prefs,final Context context){
		boolean savedOnServer = prefs.getBoolean(USER_REGISTERED_ON_SERVER, false);
		Log.i("Raavi", "User saved on Server " + savedOnServer);
		if(savedOnServer){
			return;
		}
		String profileData = prefs.getString(USER_PROFILE_SAVED_OBJECT, null);
		Log.i("Raavi", "profileData saved last time " + profileData);
		if(profileData == null){
			return;
		}
		Gson gson = new Gson();
		RegisterFacebookUserProfile registerFacebookUserProfile =  gson.fromJson(profileData, RegisterFacebookUserProfile.class);
		saveUserProfileInternal(context, registerFacebookUserProfile);
	}
	
	public static void saveUserProfile(final Context context,RegisterFacebookUserProfile registerFacebookUserProfile){
		try{
			final SharedPreferences prefs = context.getSharedPreferences(USER_PROFILE, Context.MODE_PRIVATE);
			Editor editor = prefs.edit();
			//First mark that user have saved the profile
			editor.putBoolean(USER_PROFILE_SAVED_BY_USER, true);
			Gson gson = new Gson();
			String userProfileData = gson.toJson(registerFacebookUserProfile);
			editor.putString(USER_PROFILE_SAVED_OBJECT, userProfileData);
			editor.commit();
			saveUserProfileInternal(context, registerFacebookUserProfile);
		}catch(Exception ex){
			EasyTracker.getTracker().sendException("saveUserProfile", ex, true);
		}
		
		
	}
	public static RegisterFacebookUserProfile getUserProfile(final Context context){
		RegisterFacebookUserProfile registerFacebookUserProfile = null;
		try{
			final SharedPreferences prefs = context.getSharedPreferences(USER_PROFILE, Context.MODE_PRIVATE);
			boolean alreadySaved = prefs.getBoolean(USER_PROFILE_SAVED_BY_USER, false);
			Log.i("RegisterFacebookUserProfile", "alreadySaved="+alreadySaved);
			if(alreadySaved){
				Gson gson = new Gson();
				String userProfileData = prefs.getString(USER_PROFILE_SAVED_OBJECT, null);
				Log.i("RegisterFacebookUserProfile", "USER_PROFILE_SAVED_OBJECT="+userProfileData);
				if(userProfileData != null){
					registerFacebookUserProfile = gson.fromJson(userProfileData,RegisterFacebookUserProfile.class);	
				}
			}
			
		}catch(Exception ex){
			EasyTracker.getTracker().sendException("getUserProfile", ex, true);
		}
		return registerFacebookUserProfile;
		
	}
	private static void saveUserProfileInternal(final Context context,RegisterFacebookUserProfile registerFacebookUserProfile){
		new AsyncTask<RegisterFacebookUserProfile, String, String>() {
			@Override
			protected String doInBackground(RegisterFacebookUserProfile... params) {
				for(int i=0;i<3;i++){
					try{
						try {
							Thread.sleep((i)*2*2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						Log.i("Ravi","params[0].getDeviceRegId()="+params[0].getDeviceRegId());
						DataServices.getInstance().RegisterFacebookUserProfile(params[0]);
						break;
					}catch(Exception ex){
						Log.i("Ravi", "Exception while saving user profile on server ,will wait for " + (i+1)*2 + " seconds before retrying");
						EasyTracker.getTracker().sendException("DataServices.RegisterFacebookUserProfile", ex, true);
						ex.printStackTrace();
						
						if(params[0].getDeviceRegId() == null || params[0].getDeviceRegId().trim().isEmpty()){
							params[0].setDeviceRegId(GcmUtil.getGcmDeviceRegistrationId(context));
						}
					}
				}
				return null;
			}
			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
			}
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
			}
		}.execute(registerFacebookUserProfile);
	}
}
